<template>
  <t-card :bordered="false">
    <!-- 自定义搜索 -->
    <custom-search ref="customSearchRef" v-slot="{ params }"  @submit="handleInitTable">
      <t-col :span="3">
        <t-form-item label="阶段名称" name="name">
          <t-input v-model:value="params.name" clearable placeholder="" />
        </t-form-item>
      </t-col>
      
    </custom-search>
    <!-- 自定义表格 -->
    <custom-table
      ref="customTableRef"
      row-key="id"
      :columns="columns"
      :api="engineeringMaterialSpeedConfigCRUD.page"
      :on-before-set-data="handleTableSetData"
      column-controller-key="EngineeringMaterialList"
    >
      <template #topContent>
        <div style="margin-bottom: var(--td-comp-margin-xxl);">
          <t-button
           v-permission="['system:engineering-material-speed-config:create']"
            @click="handleOpenDialog('create', { 
                status: '2',
              })"
          >
            新建施工材料进度
          </t-button>
        </div>
      </template>
    
   
      <template #messageModelCode="{ row }">
        <t-tag
            style="margin-right: 4px;margin-bottom: 4px;"
            v-for="(tag, index) in row.messageModelIds"
            :key="index"
            theme="primary"
            :closable="false"
            :disabled="true"
          >
            {{ tag.modelName }}
          </t-tag>
      </template>
      <template #status="{ row }">
        <t-switch
          v-if="row.status"
          v-model:value="row.status"
          :custom-value="['1', '2']"
          :loading="row.loading"
          @change="handleChangeStatus(row)"
        />
      </template>
      <template #createTime="{ row }">
        {{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>


      
      <template #operation="{ row }">
        <t-space break-line>
          <t-link
            v-permission="['system:engineering-material-speed-config:query']"
            theme="primary"
            @click="handleOpenDialog('read', { id: row.id })"
          >
            详情
          </t-link>
          <t-link
           v-permission="['system:engineering-material-speed-config:update']"
            theme="primary"
            @click="handleOpenDialog('update', { id: row.id })"
          >
            编辑
          </t-link>
          <t-popconfirm content="确认要删除该项吗？" @confirm="handleDelete({ id: row.id })">
            <t-link theme="danger" v-permission="['system:engineering-material-speed-config:delete']"> 删除 </t-link>
          </t-popconfirm>
        </t-space>
      </template>
    </custom-table>
    <!-- 自定义对话框 -->
    <custom-dialog
      ref="customDialogRef"
      v-slot="{ formData, readonly }"
      :api-map="engineeringMaterialSpeedConfigCRUD"
      header="*施工材料进度"
      :on-before-set-data="handleDialogSetData"
      :on-before-save-data="handleDialogSaveData"
      @request-success="handleDialogRequestSuccess"
    >
      
      <t-form-item label="阶段名称" name="name" :rules="[{ required: true, message: '请输入阶段名称' }]">
        <t-input v-model:value="formData.name" placeholder="请输入阶段名称" clearable :readonly="readonly" />
      </t-form-item>
      <t-form-item label="消息模板" name="messageModelIds" :rules="[{ required: true, message: '请输入消息模板' }]">
         <!-- 选择消息模板 -->
         <message-template-selector 
          v-model:selectedMessageIds="formData.messageModelIds" 
          :readonly="readonly"
         />
      </t-form-item>
      <t-form-item label="是否启用" name="status" :rules="[{ required: true, message: '请选择是否启用' }]" v-if="formData.status">
        <t-switch v-model:value="formData.status" :custom-value="['1', '2']" :disabled="readonly" />
      </t-form-item>
      
      
      
      


    </custom-dialog>
  </t-card>
</template>


<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin, TableCol } from 'tdesign-vue-next';
import { onMounted, ref, useTemplateRef, watch } from 'vue';

import { engineeringMaterialSpeedConfigCRUD } from '@/api/config/common-config';
import { messageTemplateCRUD } from '@/api/config/message-template';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import MessageTemplateSelector from '@/components/message-template-selector/index.vue'
import { useDictionaryStore } from '@/store';

// 字典仓库
const dictionaryStore = useDictionaryStore();
// 自定义搜索ref
const customSearchRef = useTemplateRef('customSearchRef');
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// columns
const columns: TableCol[] = [
  { colKey: 'name', title: '阶段名称' },
  { colKey: 'messageModelCode', title: '消息模板' },
  { colKey: 'status', title: '是否启用'},
  { colKey: 'createTime', title: '创建时间', width: 180 },
  { colKey: 'operation', title: '操作', width: 160, fixed: 'right' },
];


// 处理初始化表格
const handleInitTable = () => {
  const params = { ...customSearchRef.value.params };
  customTableRef.value.initTable(params);
};
// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};
onMounted(() => {
  handleGetMessageModelList();
});
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  customDialogRef.value.open(mode, params);
};
// 处理对话框保存数据
const handleDialogSaveData =(params: Record<string, any>)=>{
  
  params.messageModelCode = params.messageModelIds[0].id

};
// 处理对话框设置数据
const handleDialogSetData = (params: Record<string, any>) => {
  params.messageModelIds = messageModelList.value.filter(obj => params.messageModelCode==obj.id)
  console.log(params.messageModelIds,'params.messageModelIds',messageModelList.value,'messageModelList.value');
  
  
};

// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleInitTable();
  if (result.mode === 'update') handleRefreshTable();
};
// 处理删除
const handleDelete = (params: Record<string, any>) => {
  engineeringMaterialSpeedConfigCRUD
    .delete(params)
    .then(() => {
      MessagePlugin.success('删除成功');
      handleRefreshTable();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 处理表格设置数据
const handleTableSetData = (data: any) => {
  console.log(messageModelList.value,'table');
  
  data.list.forEach((item:any) => {
    item.messageModelIds = messageModelList.value.filter(obj => item.messageModelCode==obj.id)
  });
  
  return data
};

// 全部消息模板
const messageModelList = ref([])
// 获取所有的消息配置模板
const handleGetMessageModelList = () => {
  const requestParams = {
    pageSize:-1
  }
  messageTemplateCRUD.page(requestParams).then((data)=>{
    messageModelList.value = data.list
    handleInitTable();
    
  })
}
const handleChangeStatus = (row: Record<string, any>) => {
  row.loading = true;
  const params = { ...row };
  engineeringMaterialSpeedConfigCRUD
    .update(params)
    .then(() => {
      MessagePlugin.success('编辑成功');
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    })
    .finally(() => {
      row.loading = false;
      handleRefreshTable();
    });
};
</script>

<style lang="less" scoped>
:deep(.t-form__controls-content) {
  flex-wrap: wrap;
}
</style>


